# -*- encoding: UTF-8 -*-

import datetime
import pandas as pd
import simpy
import random

from Airplane import *

class TaxiWaySystem:
    """ 机场滑行道系统
    """
    def __init__(self):
        self.count_airplane = 0

class AirportSimulator:
    """ 机场仿真器主类
    """
    def __init__(
            self, env, 
            flight_table,
            num_runways=2, 
            num_parking_bays=8,
            num_ground_services_groups=2
            ):

        self.env = env

        self.flight_table = flight_table

        self.runways = simpy.Resource(
                env = env, 
                capacity=num_runways
                )
        self.parking_bays = simpy.Container(
                env = env, 
                capacity=num_parking_bays
                )
        self.ground_services_groups = simpy.Resource(
                env = env, 
                capacity=num_ground_services_groups 
                )

        self.taxi_way_system = TaxiWaySystem()

        self.result_df_ = pd.DataFrame(
            [],
            columns=[
            'name', 
            'from_city', 
            'from_airport', 
            'flight_miles', 
            'arrival_time', 
            'airline_company',
            'takeoff_time']
        ).T

        self.env.process(
            self.Source()
            )

    def Source(self):
        for i in range(len(self.flight_table)):
            current_sample = self.flight_table.iloc[
                i, :
                ]
            
            select_column = current_sample[
                    'arrival_time'
                    ]
            arrivial_time = (
                select_column.hour * 60 + select_column.minute
                )

            if arrivial_time > self.env.now:
                yield self.env.timeout(
                    (arrivial_time - self.env.now)
                    )
    
            self.env.process(
                self.airlinearrivalControl(
                    i, current_sample
                    )
            )

    def airlinearrivalControl(
            self, 
            airline_id, 
            airline_df
            ):

        df_iter = airline_df.copy()

        current_flight = Airplane(
            self.env,
            airline_id,
            airline_df,
            self
            )
        
        current_flight.process()
        while current_flight.is_left != True:
            yield self.env.timeout(1)
        
        takeoff_time = current_flight.takeoff_time
        df_iter['takeoff_time'] = takeoff_time
        self._concat_result(df_iter)

    def _concat_result(self, df_to_concat):
        self.result_df_ = pd.concat(
            [
                self.result_df_, 
                df_to_concat
            ], 
            axis=1,
            ignore_index=True
            )
        # self.result_df_ = self.result_df_.reset_index()

    @property
    def result(self):
        res = self.result_df_.T # 转置原始结果
        zeroday = datetime.date(1970, 1, 1)

        res['arrival_time'] = res['arrival_time'].apply(
            lambda x: datetime.datetime.combine(
                zeroday, x
                ) 
        )
        
        res['takeoff_time'] = pd.to_datetime(
            res['takeoff_time'], 
            unit='m'
            )

        res['stay_time'] = (
            res['takeoff_time'] - res['arrival_time']
            ).dt.total_seconds() / 60

        res = res.drop('index', axis=1)
        # 原来数据表里带进来的 index
        # 没有用了已经
        return res
